<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\ApiController;
use App\Models\GoodItem;
use App\Models\GoodOption;
use Illuminate\Http\Request;
use App\Models\Good as TGood;

class Good extends ApiController{
    public function index(Request $req){
        $gid = $req->post('gid',0);
        $good = TGood::select('id','title','logo','rule')->where('status',0)->find($gid);
        if (!$good) wxresp(0,'商品已下架');
        $good->logo = getImage($good->logo,1);
        $ops = GoodOption::where('gid',$gid)->where('status',0)->orderByRaw('oldprice+0')->get()->toArray();
        $list = [];
        if ($ops) {
            $min = 100;
            foreach ($ops as $v) {
                $price = GoodItem::where('oid',$v['id'])->where('status',0)->min('costprice');
                if ($price > 0) {
                    $price += $v['marketprice'];
                    $o = array('id'=>$v['id'],'title'=>$v['title'],'oldprice'=>$v['oldprice'],'pay'=>round($price,2),'discount'=>round($price/$v['oldprice']*10,1)*10);
                    $min = min($min,$o['discount']);
                    if (!isset($list[$v['ptitle']])) $list[$v['ptitle']] = [];
                    $list[$v['ptitle']][] = $o;
                }
                $items = [];
                foreach ($list as $p => $v) {
                    $items[] = array('title'=>$p,'list'=>$v);
                }
            }
            $good->list = $items;
        }
        $sharedata = array(
                'title'=> $good->title,
                'imgUrl'=> $good->logo,
                'desc'=>"限时{$min}折起",
                'link'=>"https://".$req->host()."/".$req->shopagent->code."/#/pages/index/detail?gid=".$gid
        );
        wxresp(1,['good'=>$good,'sharedata'=>$sharedata]);
    }
}